package com.taotao.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.taotao.common.enums.OperateType;
import com.taotao.common.utils.*;
import com.taotao.mapper.*;
import com.taotao.mapperCust.CommonMapperCust;
import com.taotao.mapperCust.EyGoodsMapperCust;
import com.taotao.pojo.*;
import com.taotao.service.OperateLogService;
import com.taotao.service.ParamService;
import com.taotao.service.TaskService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

@Service
public class TaskServiceImpl implements TaskService {

	@Autowired
	EyGoodsMapper eyGoodsMapper;
	@Autowired
	EyGoodsMapperCust eyGoodsMapperCust;
	@Autowired
	EyMemberMapper eyMemberMapper;
	@Autowired
	EyCategoryMapper eyCategoryMapper;
	@Autowired
	EyPictureMapper eyPictureMapper;
	@Autowired
	EyImportBatchMapper eyImportBatchMapper;
	@Autowired
	EyChinaMapper eyChinaMapper;
	@Autowired
	ParamService paramService;
	@Autowired
	OperateLogService operateLogService;
	@Autowired
	CommonMapperCust commonMapperCust;
	

	@Override
	public void setGoodsTop() {
		EyGoodsExample example = new EyGoodsExample();
		com.taotao.pojo.EyGoodsExample.Criteria criteria = example.createCriteria();
		example.setOrderByClause(" update_time asc ");
		PageHelper.startPage(1, 10);
		List<EyGoods> listPic = eyGoodsMapper.selectByExample(example);

		Random r = new Random();
		int nextInt = r.nextInt(8); // 取随机数

		EyGoods eyGoods = listPic.get(nextInt);

		Calendar c = new GregorianCalendar();
		Date date = new Date();
		c.add(Calendar.SECOND, -40);// 把日期往后增加SECOND 秒.整数往后推,负数往前移动
		date = c.getTime(); // 这个时间就是日期往后推一天的结果
		String str = DateUtil.format2.format(date);
		eyGoods.setUpdateTime(str);

		eyGoodsMapper.updateByPrimaryKey(eyGoods);

	}

	@Override
	public void importData(String sourceId,String page) {
		try {
//			String secretId = paramService.getParam("tencent_secretId");
//			String secretKey = paramService.getParam("tencent_secretKey");
//			String bucket = paramService.getParam("tencent_bucket");
//			String region = paramService.getParam("tencent_region");
//			String baseUrl = paramService.getParam("tencent_baseUrl");
//			TencenUploadUtil.init(secretId, secretKey, bucket, region, baseUrl);

			EyCategoryExample exampleCategory = new EyCategoryExample();
			com.taotao.pojo.EyCategoryExample.Criteria criteriaCategory = exampleCategory.createCriteria();
			if(StringUtils.isNotBlank(sourceId)){
				criteriaCategory.andSourceIdEqualTo(sourceId);
			}else{
				criteriaCategory.andSourceIdIsNotNull();
			}
			List<EyCategory> listCategory = eyCategoryMapper.selectByExample(exampleCategory);
			Integer p;
			if(StringUtils.isBlank(page)){
				p = 1;
			}else{
				p=Integer.parseInt(page);
			}
			for (EyCategory c : listCategory) {
				for (int i=p;i <= 50; i++) {
					System.out.println("分类id:" + c.getSourceId() + ",分类名称:" + c.getCategoryNameEn() + ",第" + i + "页");
					boolean process = this.process(c, i, 20);
					if (process) {
						System.out.println("本页数据已经存在，结束分页处理");
						break;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Transactional
	public boolean process(EyCategory category, Integer page, Integer per_page) throws Exception {
		String url="";
		if("100".equals(category.getSourceId())){ //免费赠品
			url="https://v3.movinsale.com/v3/products/freebies?page="+page+"&per_page=20";
		}else{
			url ="https://v3.movinsale.com/v3/products?page="+page+"&per_page=20&category_id="+category.getSourceId();
		}
		String sr = HttpRequest.sendGet(url);
		
		JSONObject json = JSONObject.parseObject(sr);
		System.out.println("获取数据-->"+json.toJSONString());
		
		String items = String.valueOf(json.get("items"));
		String totalCount = String.valueOf(json.get("total_count"));
		JSONArray itemsArray = JSONObject.parseArray(items);
		int repeat = 0;
		for (int i = 0; i < itemsArray.size(); i++) {
			JSONObject item = (JSONObject) itemsArray.get(i);
			String id = String.valueOf(item.get("id"));
			String name = String.valueOf(item.get("name"));
			String detail = String.valueOf(item.get("detail"));
			String price = String.valueOf(item.get("price"));

			String province = String.valueOf(item.get("province"));
			JSONObject provinceJson = JSONObject.parseObject(province);
			String provinceId = String.valueOf(provinceJson.get("id"));
			String provinceEnUs = String.valueOf(provinceJson.get("en_us"));

			String photos = String.valueOf(item.get("photos"));
			JSONArray photosArray = JSONObject.parseArray(photos);

			String city = String.valueOf(item.get("city"));
			JSONObject cityJson = JSONObject.parseObject(city);
			String cityId = String.valueOf(cityJson.get("id"));
			String cityEnUs = String.valueOf(cityJson.get("en_us"));

			String district = String.valueOf(item.get("district"));
			JSONObject districtJson = JSONObject.parseObject(district);
			String districtId = String.valueOf(districtJson.get("id"));
			String districtEnUs = String.valueOf(districtJson.get("en_us"));


			String categoryStr = String.valueOf(item.get("category"));
			JSONObject categoryJson = JSONObject.parseObject(categoryStr);
			String categoryId = String.valueOf(categoryJson.get("id"));
			String categoryName = String.valueOf(categoryJson.get("name"));

			String user = String.valueOf(item.get("user"));
			JSONObject userJson = JSONObject.parseObject(user);
			String userId = String.valueOf(userJson.get("id"));
			String nickname = String.valueOf(userJson.get("nickname"));
			String avatar = String.valueOf(userJson.get("avatar"));
			String wechat = String.valueOf(userJson.get("wechat"));

			EyMember member = new EyMember();
			member.setSourceId(userId);
			EyMemberExample exampleMember = new EyMemberExample();
			com.taotao.pojo.EyMemberExample.Criteria criteriaMember = exampleMember.createCriteria();
			criteriaMember.andSourceIdEqualTo(userId);
			List<EyMember> listMember = eyMemberMapper.selectByExample(exampleMember);
			if (listMember != null && listMember.size() > 0) {
				member = listMember.get(0);
				member.setPublishNum(member.getPublishNum() + 1);
				eyMemberMapper.updateByPrimaryKey(member);
			} else {
				String avatarUrl = "https://img.movinsale.com/images/portraits/" + avatar;
				try {
					avatarUrl = this.uploadPic(avatarUrl,avatar,"");
				} catch (Exception e) {
					e.printStackTrace();
					continue;
				}
				member.setNickName(nickname);
				member.setAvatarUrl(avatarUrl);
				if (StringUtils.isNotBlank(wechat)) {
					member.setWechat(wechat);
				}
				member.setServiceNum(0);
				member.setCollectNum(0);
				member.setPublishNum(1);
				member.setPublishNumAble(100);
				member.setProvince(provinceEnUs);
				member.setCity(cityEnUs);
				member.setCountry("China");

				member.setCreateTime(DateUtil.getDateAndTime());
				member.setUpdateTime(DateUtil.getDateAndTime());
				eyMemberMapper.insert(member);
			}

			//goods信息不同步，自同步member信息
			EyGoodsExample exampleGoods = new EyGoodsExample();
			com.taotao.pojo.EyGoodsExample.Criteria criteriaGoods = exampleGoods.createCriteria();
			criteriaGoods.andSourceIdEqualTo(id);
			List<EyGoods> listGoods = eyGoodsMapper.selectByExample(exampleGoods);
			if (listGoods != null && listGoods.size() > 0) {
				repeat++;
				continue;
			}

			EyCategoryExample exampleCategory = new EyCategoryExample();
			com.taotao.pojo.EyCategoryExample.Criteria criteriaCategory = exampleCategory.createCriteria();
			criteriaCategory.andSourceIdEqualTo(categoryId);
			List<EyCategory> listCategory = eyCategoryMapper.selectByExample(exampleCategory);

			EyGoods goods = new EyGoods();
			goods.setSourceId(id);
			goods.setMemberId(member.getId());
			goods.setTitle(name);
			goods.setDetails(detail);
			goods.setPrice(price);
			goods.setProvince(provinceId);
			goods.setCity(cityId);
			goods.setStatus("1");
			goods.setAddress(cityEnUs + " " + districtEnUs);
			goods.setDistrict(districtId);
			goods.setMobile("");
			goods.setCollectNum(new Random().nextInt(10));
			goods.setLookupNum(new Random().nextInt(50));
			goods.setCategoryId(listCategory.get(0).getId());
			goods.setCreateTime(DateUtil.getDateAndTime());
			goods.setUpdateTime(DateUtil.getDateAndTime());
			eyGoodsMapper.insert(goods);

			String imageUrlFirst="";
			for (int j = 0; j < photosArray.size(); j++) {
				String photo = String.valueOf(photosArray.get(j));
				String imgUrl = "https://img.movinsale.com/images/products/" + photo;
				String imageUrl="";
				try {
					imageUrl = this.uploadPic(imgUrl,photo,String.valueOf(goods.getId()));
				} catch (Exception e) {
					e.printStackTrace();
					continue;
				}
				System.out.println(imageUrl);
				EyPicture pic = new EyPicture();
				pic.setGoodsId(goods.getId());
				pic.setImageUrl(imageUrl);
				pic.setImageIndex(String.valueOf(j));
				pic.setUpdateTime(DateUtil.getDateAndTime());
				pic.setCreateTime(DateUtil.getDateAndTime());
				eyPictureMapper.insert(pic);
				
				if(j==0){
					imageUrlFirst=imageUrl;
				}
			}
			goods.setImageUrl(imageUrlFirst);
			eyGoodsMapper.updateByPrimaryKey(goods);
		}

		EyImportBatch batch = new EyImportBatch();
		batch.setCategoryId(Integer.parseInt(category.getSourceId()));
		batch.setType("1");
		batch.setDetails("执行批次page:" + page + ",per_page:" + per_page + "分类id:" + category.getCategoryNameEn() + ",分类:"
				+ category.getSourceId() + ",totalCount:" + totalCount + ",repeat:" + repeat);
		batch.setCreateTime(DateUtil.getDateAndTime());
		eyImportBatchMapper.insert(batch);

		return itemsArray.size() == repeat;

	}

	private String uploadPic(String imgUrl,String photo,String goodsId)  throws Exception {
		
		if(StringUtils.isBlank(photo)|| "null".equalsIgnoreCase(photo)){
			String defaultImage="https://easygo-1256152350.cos.ap-shanghai.myqcloud.com/easygoshPath/public/default.png";
			return defaultImage;
		}
		
		String uploadFilePath = paramService.getParam("upload_file_path");
		String uploadFileFolder = paramService.getParam("upload_file_folder");

		String fileName=photo.substring(photo.indexOf("/")+1);
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH) + 1;
		int day = calendar.get(Calendar.DAY_OF_MONTH);

		uploadFilePath = String.format("%s/%s/", uploadFilePath, uploadFileFolder);
		File validateCodeFolder = new File(uploadFilePath);
		if (!validateCodeFolder.exists()) {
			validateCodeFolder.mkdirs();
		}

		byte[] bs=this.getImageFromNetByUrl(imgUrl);
		InputStream in = new ByteArrayInputStream(bs);
		File f = new File(uploadFilePath, fileName);// 可以是任何图片格式.jpg,.png等
		FileOutputStream fos = new FileOutputStream(f);
		byte[] b = new byte[1024];
		int nRead = 0;
		while ((nRead = in.read(b)) != -1) {
			fos.write(b, 0, nRead);
		}
		fos.close();
		in.close();

		String fileNameCos = fileName;

		String fp = uploadFilePath + "/" + fileName;
		String fpCos = uploadFilePath + "/" + fileNameCos;
		PicUtil.commpressPicForScale(fp, fpCos);

		File fcos = new File(fpCos);
		String basePath="";
		if(StringUtils.isNotBlank(goodsId)){
			basePath = String.format("%s/%s/%s/%s/%s", uploadFileFolder, year, month, day, goodsId);
		}else{
			basePath = String.format("%s/%s/%s/%s", uploadFileFolder, year, month, day);
		}
		
		String path = String.format("/%s/%s", basePath, fileNameCos);
		String imageUrl = TencenUploadUtil.uploadFile(path, fcos);
		
//		FileUtils.forceDelete(new File(fp)); // 删除临时文件
		FileUtils.forceDelete(new File(fpCos)); // 删除临时文件  源文件和压缩文件在同一个目录 删除一个即可
		
		return imageUrl;
	}

	public static byte[] getImageFromNetByUrl(String strUrl)  throws Exception {
	      try{
				URL url = new URL(strUrl);
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setRequestMethod("GET");
				conn.setConnectTimeout(5*1000);
				InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据
				byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据
				return btImg;
			}catch (Exception e) {
				e.printStackTrace();
			}return null;
		}


	public static byte[] readInputStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[10240];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();
	}

	@Override
	public void transferData() {
		Integer transferDataNum = Integer.parseInt(paramService.getParam("transferDataNum"));
		List<EyGoods> goods=eyGoodsMapperCust.queryTransferGoods(transferDataNum);
		System.out.println(goods.toString());
		for(EyGoods g:goods){
			Integer memberId=g.getMemberId();
			Integer goodsId = g.getId();
			EyMember member = eyMemberMapper.selectByPrimaryKey(memberId);
			String sourceId = member.getSourceId();
			
			List<EyMember> memberList=eyGoodsMapperCust.queryMemberBySourceId(sourceId);
			if(memberList==null || memberList.size()==0){
				member.setId(null);
				member.setCreateTime(DateUtil.getDateAndTime());
				member.setUpdateTime(DateUtil.getDateAndTime());
				eyGoodsMapperCust.insertEyMember(member);
				member.setPublishNum(1);
				memberId=member.getId();
			}else{
				member.setPublishNum(member.getPublishNum() + 1);
				memberId=memberList.get(0).getId();
			}
			
			g.setId(null);
			g.setMemberId(memberId);
			g.setCollectNum(new Random().nextInt(5));
			g.setLookupNum(new Random().nextInt(50));
			g.setCreateTime(DateUtil.getDateAndTime());
			g.setUpdateTime(DateUtil.getDateAndTime());
			eyGoodsMapperCust.insertEyGoods(g);
			
			EyPictureExample examplePic = new EyPictureExample();
			com.taotao.pojo.EyPictureExample.Criteria criteriaPic = examplePic.createCriteria();
			criteriaPic.andGoodsIdEqualTo(goodsId);
			List<EyPicture> listPic = eyPictureMapper.selectByExample(examplePic);
			for(EyPicture p:listPic){
				p.setGoodsId(g.getId());
				p.setCreateTime(DateUtil.getDateAndTime());
				p.setUpdateTime(DateUtil.getDateAndTime());
				eyGoodsMapperCust.insertEyPicture(p);
			}
		}
		
	}

	@Override
	public void goodsInvalid() {
		EyGoodsExample example = new EyGoodsExample();
		com.taotao.pojo.EyGoodsExample.Criteria criteria = example.createCriteria();
		criteria.andStatusEqualTo(Constants.num_1);
		example.setOrderByClause("  IFNULL(updated_at,create_time) asc  ");
		List<EyGoods> listGoods = eyGoodsMapper.selectByExample(example);
		if(listGoods!=null && listGoods.size()>Integer.parseInt(Constants.num_2000)){
			int size=listGoods.size();
			int deleteNum=Integer.parseInt(Constants.num_2000)-size;
			for(int i=0;i<deleteNum;i++){
				EyGoods goods=listGoods.get(i);
				goods.setStatus(Constants.num_100); //已售
				goods.setUpdateTime(DateUtil.getDateAndTime());
				eyGoodsMapper.updateByPrimaryKey(goods);
				operateLogService.insert(null, null,goods.getId(),OperateType.operateType_44.getDesc(),OperateType.operateType_44.getCode(),"");
				System.out.println("goodsInvalid 系统删除成功 goodId->"+goods.getId());
			}
		}else{
			System.out.println("goodsInvalid 查询有效数据量小于2000或为空，不做删除处理");
		}
	}

}
